<?php
namespace Home\Logic;
use Think;
vendor('WxpayAPI.lib.WxPay#Api');
include  VENDOR_PATH."WxpayAPI/lib/WxPay.Notify.php";

class RechargeLogic extends \WxPayNotify {

	//查询订单
	public function Queryorder($transaction_id)
	{
		$input = new \WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$result = \WxPayApi::orderQuery($input);
		if(array_key_exists("return_code", $result)
			&& array_key_exists("result_code", $result)
			&& $result["return_code"] == "SUCCESS"
			&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		return false;
	}

	//重写回调处理函数
	public function NotifyProcess($data, &$msg)
	{

		Think\Log::write(json_encode(print_r($data,true)));
		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";

			Think\Log::write($msg);
			return false;
		}
		//查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";

			Think\Log::write($msg);
			return false;
		}


		$order_no = $data['attach']; // 订单号
		$transaction_id = $data['transaction_id'];
		$RLMomel = M('RechargeLog');
		$MMomel = D('Member');

		//判断是否支付
		$is_transId = $RLMomel->where(array('trans_id'=>$transaction_id))->find();
		//判断订单是否存在
		$order = $RLMomel->where(array('order_no'=>$order_no))->find();
		if(empty($is_transId) && !empty($order)) {
            //完成订单,计算返利
			$save = array('pay_time'=>time(),'trans_id'=>$transaction_id,'status'=>1,'is_pay'=>1);
            $result = $RLMomel->where(array('order_no'=>$order_no))->save($save);
            if ($result) {
				//返余额
				$MMomel->where(array('uid'=>$order['uid']))->setInc('balance',$order['amount']);
				//返消费积分
                $MMomel->where(array('uid'=>$order['uid']))->setInc('score',$order['amount']);
                //记录
                $log = array(
                    'suid'=> 0, //系统管理员
                    'uid' => $order['uid'],
                    'type'=>50, // 每日奖励
                    'score'=>$order['amount'],
                    'description'=>'',
                    'order_no'=> 'YECZ'.date('YmdHms',time()),
                );
                D('IntergalLog')->update($log);

            }
        }
		echo '<xml>
			   <return_code><![CDATA[SUCCESS]]></return_code>
			   <return_msg><![CDATA[OK]]></return_msg>
			</xml>';
		exit();
	}
}